package com.ray.wms.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.check.OrderOutCheck;
import com.ray.wms.enums.OrderStatusEnum;
import com.ray.wms.service.WmsOrderOutService;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.OutService;
import com.ray.wms.table.dto.OrderDTO;
import com.ray.wms.table.dto.OrderQueryDTO;
import com.ray.wms.table.dto.OrderStatusChangeDTO;
import com.ray.wms.table.entity.WmsOrderOut;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.wms.table.params.order.OrderQueryParams;
import com.ray.wms.table.vo.order.OrderVO;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 出库相关服务
 * @Class: OrderOutApi
 * @Package com.ray.wms.api
 * @date 2020/6/3 15:09
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class OrderOutApi {

    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private WmsOrderOutService wmsOrderOutService;
    @Autowired
    private OutService outService;
    @Autowired
    private BlockDispatch<String, LoginUser, Boolean> blockDispatch;

    /**
     * 查询出库订单
     * @param queryParams
     * @return
     */
    public Result<IPage<OrderVO>> queryOrderOuts(CommonPage<OrderQueryParams,Page<OrderVO>> queryParams){
        LoginUser loginUser = LogInUserUtil.get();
        OrderQueryParams orderQueryParams = queryParams.getEntity();
        Map<String,WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        //当存在仓库参数时候  先校验仓库
        if(ObjectUtil.isNotNull(orderQueryParams) && StrUtil.isNotBlank(orderQueryParams.getWarehouseCode())){
            WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(orderQueryParams.getWarehouseCode(),loginUser);
            if(ObjectUtil.isEmpty(wmsWarehouse)){
                //结果对象
                IPage<OrderVO> pageList = new Page<>();
                pageList.setTotal(0);
                pageList.setRecords(new ArrayList<>());
                return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
            }
            wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(),wmsWarehouse);
        }
        CommonPageBuilder<OrderQueryDTO,WmsOrderOut> commonPageBuilder = new CommonPageBuilder<>(OrderQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<WmsOrderOut> page = wmsOrderOutService.page(commonPageBuilder.bulid(),loginUser);
        List<WmsOrderOut> customers = page.getRecords();
        //结果对象
        IPage<OrderVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if(ObjectUtil.isNotNull(customers)){
            pageList.setRecords(customers.stream().map(wmsOrderIn -> {
                OrderVO orderVO = new OrderVO();
                BeanUtil.copyProperties(wmsOrderIn,orderVO);
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(wmsOrderIn.getWarehouseCode());
                if(ObjectUtil.isEmpty(wmsWarehouse)){
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(wmsOrderIn.getWarehouseCode(),loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(),wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return  orderVO;
            }).collect(Collectors.toList()));
        }else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
    }

    /**
     * 出库操作
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> doOrder(String orderNo){
        ValidateUtil.hasLength(orderNo,"参数[orderNo]不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        WmsOrderOut orderOut = wmsOrderOutService.queryByOrderNo(orderNo,loginUser);
        new OrderOutCheck(orderOut).checkNull(SysMsgCodeConstant.Error.ERR10000002).canDoCheck(SysMsgCodeConstant.Error.ERR10000015);
        //更新订单状态
        OrderStatusChangeDTO orderStatusChangeDTO = new OrderStatusChangeDTO(orderNo, OrderStatusEnum.DO.getValue(),orderOut.getUpdateVersion());
        if(!wmsOrderOutService.updateStatus(orderStatusChangeDTO,loginUser)){
            log.info("更新订单状态异常,参数：{}", JSON.toJSONString(orderStatusChangeDTO));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //处理入库操作
        outService.orderOut(new OrderDTO(orderOut.getOrderNo(),orderOut.getWarehouseCode(),orderOut.getBusinessOrderNo()),loginUser);
        //更改业务单号状态
        String strategy = orderOut.getBusinessCode().substring(0,2);
        blockDispatch.dispatch("out",strategy,orderOut.getBusinessCode(),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,orderNo);
    }


    /**
     * 取出库操作
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> doCancelOrder(String orderNo){
        ValidateUtil.hasLength(orderNo,"参数[orderNo]不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        WmsOrderOut orderOut = wmsOrderOutService.queryByOrderNo(orderNo,loginUser);
        new OrderOutCheck(orderOut).checkNull(SysMsgCodeConstant.Error.ERR10000002).cancelCheck(SysMsgCodeConstant.Error.ERR10000015);
        //更新订单状态
        OrderStatusChangeDTO orderStatusChangeDTO = new OrderStatusChangeDTO(orderNo, OrderStatusEnum.CANCEL.getValue(),orderOut.getUpdateVersion());
        if(!wmsOrderOutService.updateStatus(orderStatusChangeDTO,loginUser)){
            log.info("更新订单状态异常,参数：{}", JSON.toJSONString(orderStatusChangeDTO));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //处理入库操作
        outService.orderCancel(new OrderDTO(orderOut.getOrderNo(),orderOut.getWarehouseCode(),orderOut.getBusinessOrderNo()),loginUser);
        String strategy = orderOut.getBusinessCode().substring(0,2);
        blockDispatch.dispatch("cancel",strategy,orderOut.getBusinessCode(),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,orderNo);
    }



}
